//
//  AppDelegate.m
//  beautyAccompany
//
//  Created by xiaocankeji on 15/10/29.
//  Copyright © 2015年 xiaocankeji. All rights reserved.
//

#import "AppDelegate.h"
//友盟
#import "UMSocialWechatHandler.h"
#import "UMSocialQQHandler.h"
#import "UMSocialSinaHandler.h"
#import <AVOSCloudCrashReporting/AVOSCloudCrashReporting.h>
#import "AppDelegate+EaseMob.h"
#import "HomeViewController.h"
#import <CommonCrypto/CommonDigest.h>
#import <AlipaySDK/AlipaySDK.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>//引入地图功能所有的头文件
@interface AppDelegate ()<BMKGeneralDelegate>
@property NSString *wxCode;
@property NSString *wxAccessToken;
@property NSString *wxOpenid;
@end

@implementation AppDelegate

- (void)avosRegisterSubclass
{
    //leancloud
    [MPUser registerSubclass];
    [MPGallery registerSubclass];
    [MPGift registerSubclass];
    [MPGiftRecord registerSubclass];
    [MPIncomeRecord registerSubclass];
    [MPFeedback registerSubclass];
    [MPCategory registerSubclass];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    //注册失败
    NSLog(@"%@",error);
}
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
   
    AVInstallation *currentInstallation = [AVInstallation currentInstallation];
    [currentInstallation setDeviceProfile:AVOS_APP_DeviceProfile];
    [currentInstallation setDeviceTokenFromData:deviceToken];
    [currentInstallation saveInBackground];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    _connectionState = eEMConnectionConnected;
    
    //self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    //self.window.backgroundColor = [UIColor whiteColor];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(loginStateChange:)
                                                 name:KNOTIFICATION_LOGINCHANGE
                                               object:nil];
    
    //推送配置
    if (IS_IOS8) {
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert| UIUserNotificationTypeBadge| UIUserNotificationTypeSound categories:nil];
        [application registerUserNotificationSettings:settings];
        [application registerForRemoteNotifications];
    }else{
        [application registerForRemoteNotificationTypes:
         UIRemoteNotificationTypeBadge |
         UIRemoteNotificationTypeAlert |
         UIRemoteNotificationTypeSound];
    }
////    //设置导航栏颜色
   [[UINavigationBar appearance] setBarStyle:UIBarStyleBlackOpaque];//导航栏颜色
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];//状态栏颜色
   [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];//导航栏back等颜色
    [[UINavigationBar appearance]setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:18]}];////导航栏Title颜色
   [[UINavigationBar appearance] setBackgroundImage:[UIImage imageWithColor:RGBA(20, 25, 46, 1)] forBarMetrics:UIBarMetricsDefault];
////
    //百度地图
    _mapManager = [[BMKMapManager alloc]init];
    // 如果要关注网络及授权验证事件，请设定     generalDelegate参数
    BOOL ret = [_mapManager start:kBaiduMapAppKey  generalDelegate:nil];
    if(!ret){
        NSLog(@"错误的");
    }
    
    
    //友盟
    [UMSocialData setAppKey:UM_KEY];
    [UMSocialConfig hiddenNotInstallPlatforms:@[UMShareToQQ,UMShareToQzone,UMShareToWechatSession,UMShareToWechatTimeline]];
    //设置微信AppId,设置分享url,默认使用友盟的网址
    [UMSocialWechatHandler setWXAppId:@"wxea476b03fadc1c2a" appSecret:@"77d1eabc50fac1436a2949dd7fd6af8c" url:@"http://www.pocketsweet.com/wap"];
    //    //设置分享到QQ空间的应用Id,和分享url 链接
    [UMSocialQQHandler setQQWithAppId:@"1104588970" appKey:@"JVSuqFVQjNWJJvSI" url:@"http://www.pocketsweet.com/wap"];
    //    //设置支持没有客户端情况下使用SSO授权
    
    [UMSocialQQHandler setSupportWebView:YES];
    [UMSocialSinaHandler openSSOWithRedirectURL:WEIBO_REDIRECT_URI];
    //微信
    [WXApi registerApp:@"wxaa055b4833fdbf4a"];
    
    

    
    
    [self avosRegisterSubclass];
    //崩溃使用
    [AVOSCloudCrashReporting enable];
     [AVOSCloud setApplicationId: AVOS_APP_ID clientKey: AVOS_APP_KEY];
    [AVAnalytics trackAppOpenedWithLaunchOptions:launchOptions];
  [self easemobApplication:application didFinishLaunchingWithOptions:launchOptions];
    
    MPUser *user = [MPUser currentUser];
    
    if (user) {
        if (!user.nickname) {
            [MPUser logOut];
        }
        if (user.isUserInited) {
            if (![AVInstallation currentInstallation].installationId) {
                [self installation];
            }
            
            
        }else{
            [MPUser logOut];
        }
        
        
        
    }else{
        
    }
    
    
   
    //判断leancloud有没有登录
    
    
    
    self.window.backgroundColor = [UIColor whiteColor];
    HomeViewController *homeVC = [[HomeViewController alloc] init];
   UINavigationController *homeNa = [[UINavigationController alloc] initWithRootViewController:homeVC];
    self.window.rootViewController = homeNa;
    
    
    
    
   // [self loginStateChange:nil];
  //  [self.window makeKeyAndVisible];
    return YES;
}
-(void)installation
{
        MPUser *user = [MPUser currentUser];
        if (user.isUserInited) {
            AVInstallation *installation = [AVInstallation currentInstallation];
            NSArray *objects;
            if (user.gender==MPUserGender_MALE) {
                objects = @[user.objectId,@"SweetMale"];
            }else{
                objects = @[user.objectId,@"SweetFemale"];
            }
            [installation addUniqueObjectsFromArray:objects forKey:@"channels"];
            [installation saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
               
            }];
        }
    
}

//- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
//{
//    if (_mainController) {
//        [_mainController jumpToChatList];
//    }
//}
//
//- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
//{
//    if (_mainController) {
//        [_mainController didReceiveLocalNotification:notification];
//    }
//}
#pragma mark - private
//登陆状态改变
-(void)loginStateChange:(NSNotification *)notification
{
//    UINavigationController *nav = nil;
//    
//    BOOL isAutoLogin = [[[EaseMob sharedInstance] chatManager] isAutoLoginEnabled];
//    BOOL loginSuccess = [notification.object boolValue];
//    
//    if (isAutoLogin || loginSuccess) {//登陆成功加载主窗口控制器
//        //加载申请通知的数据
//        [[ApplyViewController shareController] loadDataSourceFromLocalDB];
//        if (_mainController == nil) {
//            _mainController = [[MainViewController alloc] init];
//            [_mainController networkChanged:_connectionState];
//            nav = [[UINavigationController alloc] initWithRootViewController:_mainController];
//        }else{
//            nav  = _mainController.navigationController;
//        }
//        
//        // 环信UIdemo中有用到Parse，您的项目中不需要添加，可忽略此处。
//        [self initParse];
//    }else{//登陆失败加载登陆页面控制器
//        _mainController = nil;
//        LoginViewController *loginController = [[LoginViewController alloc] init];
//        nav = [[UINavigationController alloc] initWithRootViewController:loginController];
//        loginController.title = NSLocalizedString(@"AppName", @"EaseMobDemo");
//        
//        // 环信UIdemo中有用到Parse，您的项目中不需要添加，可忽略此处。
//        [self clearParse];
//    }
//    
//    //设置7.0以下的导航栏
//    if ([UIDevice currentDevice].systemVersion.floatValue < 7.0){
//        nav.navigationBar.barStyle = UIBarStyleDefault;
//        [nav.navigationBar setBackgroundImage:[UIImage imageNamed:@"titleBar"]
//                                forBarMetrics:UIBarMetricsDefault];
//        
//        [nav.navigationBar.layer setMasksToBounds:YES];
//    }
//    
//    self.window.rootViewController = nav;
//    
//    [nav setNavigationBarHidden:YES];
//    [nav setNavigationBarHidden:NO];
}
//自动登录调用的方法
- (void)autologinToEasemob{
    MPUser *user = [MPUser currentUser];
    if (user == nil) {
        return;
    }
    if (MPUserStatus_DISABLE == user.status) {
        [self appout];
        return;
    }
    if (user) {
        
        [[EaseMob sharedInstance].chatManager setApnsNickname:user.nickname];
        [HUD setOnViewWithTitle:@"登录中" animated:YES];
        [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:user.objectId password:[self md5:user.objectId] completion:^(NSDictionary *loginInfo, EMError *error) {
            [HUD hideFromViewAnimated:YES];
            if (!error && loginInfo) {
                [[EaseMob sharedInstance].chatManager setIsAutoLoginEnabled:YES];
                //获取群组列表
                [[EaseMob sharedInstance].chatManager asyncFetchMyGroupsList];
                NSLog(@"登录成功");
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"logOutSucceed" object:nil];
                [[EaseMob sharedInstance].chatManager setApnsNickname:user.nickname];
                // 设置自动登录
                [self inituserdata];
                
                [[EaseMob sharedInstance].chatManager.pushNotificationOptions setDisplayStyle:ePushNotificationDisplayStyle_messageSummary];
                
                [[EaseMob sharedInstance].chatManager setIsAutoFetchBuddyList:YES];
                
                [HUD hideFromViewAnimated:YES];
            } else {
                switch (error.errorCode)
                {
                        
                        
                        
                    case EMErrorServerTooManyOperations:
                        break;
                        //                    case EMErrorNotFound:
                        //                        //不存在
                        //                        break;
                    case EMErrorNetworkNotConnected:
                        //EMErrorNetworkNotConnected
                        break;
                    case EMErrorServerNotReachable:
                        //连接服务器问题
                        break;
                        //                    case EMErrorServerAuthenticationFailure:
                        //                      //获取token失败
                        //                        break;
                        //                    case EMErrorServerTimeout:
                        //                       //连接超时
                        //                        break;
                    default:
                    {
                        [self loginFeated:user];
                    }
                        
                        break;
                }[
                  HUD hideFromViewAnimated:YES];
                
            }
        } onQueue:nil];
    }
}

- (void)loginFeated:(MPUser *)user
{
    NSDictionary *params = @{@"username": user.objectId,@"nickname":user.nickname,@"password":[self md5:user.objectId]};
    [AVCloud callFunctionInBackground:@"register" withParameters:params block:^(id object, NSError *errorr) {
        if (!errorr) {
            [HUD setOnViewWithTitle:@"登录中" animated:YES];
            NSLog(@"注册成功");
            [user refreshInBackgroundWithBlock:nil];
            // 重新登录
            [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:user.objectId password:[self md5:user.objectId] completion:^(NSDictionary *loginInfo, EMError *error) {
                [HUD hideFromViewAnimated:YES];
                if (!error && loginInfo) {
                    
                    //获取群组列表
                    [[EaseMob sharedInstance].chatManager asyncFetchMyGroupsList];
                    [[EaseMob sharedInstance].chatManager setIsAutoLoginEnabled:YES];
                    [[EaseMob sharedInstance].chatManager setApnsNickname:user.nickname];
                    
                    [[EaseMob sharedInstance].chatManager.pushNotificationOptions setDisplayStyle:ePushNotificationDisplayStyle_messageSummary];
                    NSLog(@"登录成功");
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"logOutSucceed" object:nil];
                    
                    [self inituserdata];
                    [self autoLogin];
                    [HUD hideFromViewAnimated:YES];
                    
                }else{
                    [HUD Prompt:@"登陆出错"];
                    [self appOut];
                    [HUD hideFromViewAnimated:YES];
                    return ;
                }
            } onQueue:nil];
        }else{
            
            
        }
    }];
}
-(void)appOut
{
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"OnlineTableViewReloadData" object:self userInfo:nil];
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"RecommendTableViewReloadData" object:self userInfo:nil];
    // 退订推送
    MPUser *user = [MPUser currentUser];
    if (user) {
        //退出登录
        [Utils quitLogin];
        [[EaseMob sharedInstance].chatManager asyncLogoffWithUnbindDeviceToken:NO completion:^(NSDictionary *info, EMError *error) {
            [[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"MLOUT"];
            if(error){
                [[EaseMob sharedInstance].chatManager asyncLogoffWithUnbindDeviceToken:NO completion:^(NSDictionary *info, EMError *error) {
                    [[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"MLOUT"];
                } onQueue:nil];
            }
        } onQueue:nil];
    }
}
-(void)appout
{
    
    //  [HUD Prompt:@"账号被禁用了,请联系客服"];
    [Utils alert:@"账号被禁用了,请联系客服"];
    //退出登录
    [Utils quitLogin];
    
    [[EaseMob sharedInstance].chatManager asyncLogoffWithUnbindDeviceToken:NO completion:^(NSDictionary *info, EMError *error) {
        if(error){
            [[EaseMob sharedInstance].chatManager asyncLogoffWithUnbindDeviceToken:NO completion:^(NSDictionary *info, EMError *error) {
            } onQueue:nil];
        }
    } onQueue:nil];
}
-(void)autoLogin
{
    [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:[MPUser currentUser].objectId password:[self md5:[MPUser currentUser].objectId] completion:^(NSDictionary *loginInfo, EMError *error) {
        [HUD hideFromViewAnimated:YES];
        if (!error && loginInfo) {
            NSLog(@"登录成功");
            [[EaseMob sharedInstance].chatManager setApnsNickname:[MPUser currentUser].nickname];
            // 设置自动登录
            [self inituserdata];
            [[EaseMob sharedInstance].chatManager.pushNotificationOptions setDisplayStyle:ePushNotificationDisplayStyle_messageSummary];
            [[EaseMob sharedInstance].chatManager setIsAutoLoginEnabled:YES];
            
        } else {
           
        }
    } onQueue:nil];
}

///发送系统消息
-(void)inituserdata
{
    [self installation];
    EMPushNotificationOptions *p = [[EMPushNotificationOptions alloc] init];
    p.nickname = [MPUser currentUser].nickname;
    p.displayStyle = ePushNotificationDisplayStyle_messageSummary;
    [[EaseMob sharedInstance].chatManager asyncUpdatePushOptions:p completion:^(EMPushNotificationOptions *options, EMError *error) {
        if(!error){
            // [HUD Prompt:@"设置成功"];
            NSUserDefaults *u =[NSUserDefaults standardUserDefaults];
            NSDictionary *dic = [u objectForKey: [NSString stringWithFormat:@"%@myswitchdic",[MPUser currentUser].objectId]];
            NSMutableDictionary *switchDic = [NSMutableDictionary dictionaryWithDictionary:dic];
            [switchDic setObject:@"YES" forKey:@"notification"];
            [u setObject:switchDic forKey: [NSString stringWithFormat:@"%@myswitchdic",[MPUser currentUser].objectId]];
            [u synchronize];
        }else{
            
        }
    } onQueue:nil];
    
}
- (NSString *)md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}
// 登录环信账号,主动登录调用方法,需要重新加载好友关系,喜欢的人,喜欢的文章
//
- (void)loginToEasemob{
    
    [self autologinToEasemob];
    
    MPUser *user = [MPUser currentUser];
    if (user&&[MPUser currentUser].isUserInited&&MPUserStatus_DISABLE != user.status) {
       // [self loadFrinedAndLikeData];
       
    }
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    //已经进入后台
    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"applicationDidEnterBackground"];
    [[EaseMob sharedInstance] applicationDidEnterBackground:application];
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [[EaseMob sharedInstance] applicationWillEnterForeground:application];
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    [[EaseMob sharedInstance] applicationWillTerminate:application];
    AVInstallation *currentInstallation = [AVInstallation currentInstallation];
    [currentInstallation setBadge:0];
    [currentInstallation saveEventually];
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
-(void) onResp:(BaseResp*)resp
{
    /*     ErrCode ERR_OK = 0(用户同意)
     ERR_AUTH_DENIED = -4（用户拒绝授权）
     ERR_USER_CANCEL = -2（用户取消）
     code    用户换取access_token的code，仅在ErrCode为0时有效
     state   第三方程序发送时用来标识其请求的唯一性的标志，由第三方程序调用sendReq时传入，由微信终端回传，state字符串长度不能超过1K
     lang    微信客户端当前语言
     country 微信用户当前国家信息
     */
    SendAuthResp *aresp = (SendAuthResp *)resp;
    if (aresp.errCode== 0) {
        NSString *code;
        @try {
            // 可能会出现崩溃的代码
            code = aresp.code;
            self.wxCode = code;
            [self getAccess_token];
        }
        @catch (NSException *exception) {
            // 捕获到的异常exception
        }
    }
    
}

-(void)getAccess_token  {
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",@"wxaa055b4833fdbf4a",@"c4f199bd5983ae9309c8bcb4f3bcd0e4",self.wxCode];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (data) {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                self.wxAccessToken = [dic objectForKey:@"access_token"];
                self.wxOpenid = [dic objectForKey:@"openid"];
                [self getUserInfo];
            }
        });
    });
}

-(void)getUserInfo  {
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",self.wxAccessToken,self.wxOpenid];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (data) {
                //*  @param  authData     SNS平台登录返回的用户验证数据. 必需包含字段:`id`,`access_token`,`expires_at`,`platform`
                NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                //确定账号的过期时间= 账号创建的时间 + 有效期
                NSTimeInterval secondsPerDay = (24*7) * 60 * 60;
                NSDate *tomorrow = [[NSDate alloc] initWithTimeIntervalSinceNow:secondsPerDay];
                [dic setObject:self.wxOpenid forKey:@"id"];
                [dic setObject:self.wxAccessToken forKey:@"access_token"];
                [dic setObject:tomorrow forKey:@"expires_at"];
                [dic setObject:[NSNumber numberWithInteger:2] forKey:@"platform"];
                [dic setObject:[dic objectForKey:@"headimgurl"] forKey:@"avatar"];
                [dic setObject:[dic objectForKey:@"nickname"] forKey:@"username"];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"WXLogin" object:self userInfo:dic];
                
            }
        });
    });
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    //如果极简 SDK 不可用,会跳转支付宝钱包进行支付,需要将支付宝钱包的支付结果回传给 SDK
    if ([url.host isEqualToString:@"safepay"]) {
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
    }
    if ([url.host isEqualToString:@"platformapi"]){//支付宝钱包快登授权返回 authCode
        [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
    }
    
    return [UMSocialSnsService handleOpenURL:url]|| [WXApi handleOpenURL:url delegate:self] || [AVOSCloudSNS handleOpenURL:url];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [UMSocialSnsService handleOpenURL:url]||[WXApi handleOpenURL:url delegate:self] || [AVOSCloudSNS handleOpenURL:url];
}


@end
